package com.xtxb.app.rmq.consume;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
@ServerEndpoint("/ws/{uuid}")
public class WebSocktSender {
    private static Logger log= LoggerFactory.getLogger(WebSocktSender.class);

    public void send(String uuid,String body){
        if(clients.containsKey(uuid)){
            clients.get(uuid).getAsyncRemote().sendText(body);
        }
    }

    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session,@PathParam("uuid") String uuid) {
        log.info("有新的客户端连接了: sessionID="+session.getId()+"; uuid="+uuid);
        //将新用户存入在线的组
        clients.put(uuid, session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session,@PathParam("uuid") String uuid) {
        log.info("有用户断开了, sessionID="+session.getId()+"; uuid="+uuid);
        clients.remove(uuid);
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        log.error("",throwable);
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("服务端收到客户端发来的消息: {}", message);

    }
}
